/**
 * Project Name:src-portal-webapp
 * File Name:XssSecurityFilter.java
 * Package Name:com.sf.isic.src.filter
 * Date:2017年4月10日下午1:54:57
 * Copyright (c) 2017, xutao9@sf-express.com All Rights Reserved.
 *
*/

package com.sf.iguess.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.util.WebUtils;

import com.sf.iguess.wrapper.IsicRequestWrapper;
import com.sf.iguess.wrapper.IsicXssCommonsMultipartResolver;

	
public class XSSRequestFilter extends OncePerRequestFilter {

	private MultipartResolver multipartResolver;

	// 字符集设定,web.xml中初始化
	private String encoding;

	public XSSRequestFilter() {
	}

	@Override
	protected void initFilterBean() throws ServletException {
		IsicXssCommonsMultipartResolver resolver = new IsicXssCommonsMultipartResolver();
		resolver.setServletContext(getServletContext());
		multipartResolver = resolver;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (!StringUtils.isBlank(encoding)) {
			request.setCharacterEncoding(encoding);
			response.setCharacterEncoding(encoding);
		}

		boolean multipartRequestParsed = false;
		HttpServletRequest req = new IsicRequestWrapper(request);
		// 判断当前请求,是否为multipart 类型的请求
		if (multipartResolver.isMultipart(req)) {
			req = multipartResolver.resolveMultipart(req);
			multipartRequestParsed = true;
		}

		try {
			filterChain.doFilter(req, response);
		} finally {
			if (multipartRequestParsed) {
				multipartResolver
						.cleanupMultipart(WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class));
			}
		}
	}

	// @Override
	// protected void doFilterInternal(HttpServletRequest request,
	// HttpServletResponse response, FilterChain chain)
	// throws ServletException, IOException {
	// try {
	// HttpServletRequest req = new
	// IsicRequestWrapper((HttpServletRequest)request);
	// chain.doFilter(req, response);
	// } catch (Exception e) {
	// LOG.error("Xss过滤器，包装request对象失败");
	// chain.doFilter(request, response);
	// }
	// }
}
